import { ref } from "vue";

/** 用于响应画布发生变更 */
export const cavasChanged = ref(0);

/**
 * 定位画布中已选控件的操作按钮的位置
 * @param canvasElement 画布父容器
 */
export function setPositionOfBtnGroup(canvasElement: HTMLElement) {
    if (!canvasElement) {
        return;
    }
    const selectDom = canvasElement.querySelector('.dgComponentSelected') as HTMLElement;
    if (!selectDom) {
        return;
    }

    const selectDomRect = selectDom.getBoundingClientRect();
    if (selectDomRect.width === 0 && selectDomRect.height === 0) {
        return;
    }
    const toolbar = selectDom.querySelector('.component-btn-group') as HTMLElement;
    if (toolbar) {

        const isInView = isElementInViewport(selectDom, canvasElement);
        if (!isInView) {
            toolbar.style.display = 'none';
            return;
        }
        // 计算位置
        toolbar.style.display = '';
        const toolbarRect = toolbar.getBoundingClientRect();
        const divPanel = toolbar.querySelector('div') as HTMLElement;
        if (divPanel) {
            const divPanelRect = divPanel.getBoundingClientRect();
            divPanel.style.top = toolbarRect.top + 'px';
            divPanel.style.left = toolbarRect.left - divPanelRect.width + 'px';
        }
    }
}
/**
 * 判断DOM 是否在可视区域内
 * @param el 元素
 * @param containerEl 容器
 */
function isElementInViewport(el: HTMLElement, containerEl: HTMLElement) {
    const container = containerEl.getBoundingClientRect();
    const box = el.getBoundingClientRect();
    const top = box.top >= container.top;
    const bottom = box.top <= container.bottom;
    return (top && bottom);
}
